﻿// define our state class by extending gamvas.State
gameState = gamvas.State.extend({
    init: function () {
        this.dim = gamvas.getCanvasDimension();
        this.alphabets = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        this.word = wordToFind;
        // display the game board
        this.leftOffSetBoard = 50;
        this.yPosBoard = -200;
        this.lowerLimit = Math.floor(this.dim.w / 2);
        this.fireworks = [];
        this.scoreboxes = [];
        this.playerIndex = 0;
        this.wheelIndex = 0;
        this.counter = 0;

        // get the background
        this.bg = new gamvas.Image(this.resource.getImage(baseURL+'Content/images/gamebg.jpg'));

        displayWordTiles(wordToFind, '');

        var st = gamvas.state.getCurrentState();
        var newScorebox1 = new scoreboxActor('scorebox1', -350, 80, 0, this.c);
        this.scoreboxes.push(newScorebox1);
        this.addActor(newScorebox1);
        var newScorebox2 = new scoreboxActor('scorebox2', -100, 80, 0, this.c);
        this.scoreboxes.push(newScorebox2);
        this.addActor(newScorebox2);
        var newScorebox3 = new scoreboxActor('scorebox3', 150, 80, 0, this.c);
        this.scoreboxes.push(newScorebox3);
        this.addActor(newScorebox3);

        this.wheel = new wheelActor('wheel', 0, 250);
        this.addActor(this.wheel);

        this.state = 'board';
        $('div.UserText, div.Wordhint').show();
    },

    preDraw: function(t) {
        // draw our background before camera is applied
        this.bg.draw(t);
    },

    postDraw: function (t) {
        drawPlayerTurn(this.c, this.playerIndex, this);
//        if (checkGameOver(this.tiles)) {
//            for (var i = this.tiles.length; i >= 0; i--) {
//                this.removeActor(this.tiles[i]);
//                delete this.tiles[i];
//            }
//            //gamvas.state.setState('menu');
//        }
    },

    draw: function (t) {
        while (this.fireworks.length > 0) {
            // get the current and remove it from the array
            var curr = this.fireworks.shift();
            this.addActor(new fireworkEmitter('boom'+this.counter, curr.x + 16, curr.y + 20));
            this.counter++;
        }

        if (this.state == 'waitingForSpin') {   
            if (this.playerIndex == 0) {
                return;
            }
            else {
                this.state = 'board';
            }
            $("#SpinButton").hide();
        }

        if (this.state == 'board') {        
            if (this.playerIndex == 0) {
                var sta = this;
                renderSpinButton("#SpinButton", function () { spinWheel(sta); });
                this.state = 'waitingForSpin';
            }
            else {
                spinWheel(this);
            }
        }

        if (this.state == 'wheel') {
            if (this.wheel.rotVelocity == 0) {
                var value = this.wheel.values[getWheelIndex(this.wheel.rotation)]; 
                if (value == -2) {
                    alert('lose a turn!');
                    nextPlayer(this);
                    this.state = 'board';
                }
                else if (value == -1) {
                    alert('bankrupt!');
                    this.scoreboxes[this.playerIndex].score = 0;
                    nextPlayer(this);
                    this.state = 'board';
                }
                else {
                    if (this.playerIndex == 0) {
                        this.state = 'keyboard';
                    }
                    else {
                           
                        AIPlayer(this);
                    }
                }
            }
        }
        else if (this.state == 'keyboard') {
            this.state = 'board';
            var sta = this;
            letterButtonsFromServer("#EnterText", function (letter) { guessLetter(sta, letter); });
        }
    },

    onKeyDown: function (k) {
        if (this.state == 'board') {
            if (k == gamvas.key.SPACE) {
                spinWheel(this);
            }
        }
        else if (this.state == 'keyboard') {
            if (this.playerIndex == 0) {
                guessLetter(this, k);
            }
            else {
                // cannot do anything else
            }
            this.state = 'board';
        }
        return false;
    },

//    onMouseDown: function (b, x, y) {
//        if (b == gamvas.mouse.LEFT) {
//            // get our world coordinates of the mouse screen coordinates
//            var wp = this.camera.toWorld(x, y);
//            // update our emitter position
//            this.emitter.setPosition(wp.x, wp.y);
//            // update restart (whith old particles continuing to live)
//            // if your want to force a reset, so old particles are
//            // killed immediately, use reset(true)
//            this.emitter.reset();
//        }
//    }
});

function guessLetter(st, k)
{
    if(k.length && k.length > 1)
    {
        SolveThePuzzle(st, k, st.wheel.values[getWheelIndex(st.wheel.rotation)]);
        return;
    }

//if (k >= gamvas.key.A && k <= gamvas.key.Z) {
                    var isLose = false;
                    var value = st.wheel.values[getWheelIndex(st.wheel.rotation)];
                    if (value <= 0) return;

                    
                
                    $.ajax({
                        url: guessURL,
                        type: 'post',
                        cache: false,
                        contentType: 'application/json; charset=utf-8',
                        dataType: 'json',
                        data:JSON.stringify({c: k, potentialPoints:value, playerIndex: st.playerIndex} ),
                        success: function (json) { 
                            displayWordTiles(json.word, k);

                            if (json.lettersFound == 0) {
                                alert('No letters found. :(');
                                isLose = true;

                            }
                            if (json.word.indexOf('#') == -1)
                            {
                                //player wins
                                alert('winner!');
                                window.location = highScoreURL + '?highScore=' + st.scoreboxes[st.playerIndex].score;
                                //gamvas.state.setState('menu');
                            }
                            if (isLose) {
                                nextPlayer(st);
                                this.state = 'board';
                            }
                            else {
                                st.scoreboxes[st.playerIndex].score += value * json.lettersFound;
                            }
                        },
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log("error :" + XMLHttpRequest.responseText);
                        }
                    });
//                }
}

function spinWheel(st) {
    var rotSpeed = 10 + (Math.random() % 10);
    st.wheel.rotVelocity = rotSpeed;
    st.state = 'wheel';
}

function displayWordTiles(word, letter)
{
    //alert(word);
    var state = gamvas.state.getCurrentState();
    var maxBoardLength = 20;
    var xPos = 0;
    var yPos = state.yPosBoard;
    for (var i = 0; i < word.length; i++) {
        var newTile;
        if (xPos > maxBoardLength) {
            yPos += 50;
            xPos = 0;
        }
        
        if (word[i] == ' ') {
        }
        else {
            var nextSpaceIndex = word.indexOf(' ', i);
            if (nextSpaceIndex == -1) 
                nextSpaceIndex = word.length;
            var currentWordLength = nextSpaceIndex - i;
            if (currentWordLength > maxBoardLength - xPos) {
                yPos += 50;
                xPos = 0;
                //alert(currentWordLength);
            }
            
            newTile = new tileActor('tile' + i, state.leftOffSetBoard + (32 * xPos) - state.lowerLimit, yPos, word[i]);
            if (word[i] != '#') {
                newTile.setFile(state.resource.getImage(baseURL + 'Content/images/' + word[i] + '.png'));
                if (word[i] == letter)
                    state.fireworks.push(new gamvas.Vector2D(state.leftOffSetBoard + (32 * xPos) - state.lowerLimit, yPos));
            }
        }
        state.addActor(newTile);

        xPos++;
    }     
}

//function checkGameOver(tiles) {
//    // check if game over
//    var isGameOver = true;
//    for (var i = 0; i < tiles.length; i++) {
//        if (!tiles[i].show) {
//            isGameOver = false;
//            break;
//        }
//    }
//    return isGameOver;
//}

function nextPlayer(st) {
    st.playerIndex++;
    if (st.playerIndex > 2)
        st.playerIndex = 0;   
}

function getWheelIndex(rotation) {
    var roundedRotation = Math.round(rotation * 180 / Math.PI) % 360;
    return wheelIndex = 24 - Math.ceil(roundedRotation / 15);
}

function drawPlayerTurn(ctx, playerIndex, state) {
    var dim = gamvas.getCanvasDimension();
    ctx.save();
    ctx.fillStyle = 'Navy';
    ctx.font = 'bold 23px sans-serif';
    ctx.textAlign = 'left';
    if(playerIndex == 0)
        ctx.fillText("Now it's your turn ", 10, 20);
    else
        ctx.fillText("Computer Player " + playerIndex , 10, 20);
    ctx.restore();
    for(var i = 0; i < 3; i++)
        state.scoreboxes[i].setSelected(playerIndex == i);
}

function AIPlayer(st) {
    var value = st.wheel.values[getWheelIndex(st.wheel.rotation)];
    var isLose = false;
    $.ajax({
        url: baseURL + 'Home/AIGuessLetter',
        type: 'post',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data:JSON.stringify({potentialPoints:value, playerIndex: st.playerIndex} ),
        success: function (json) {                       
            displayWordTiles(json.word, json.letter);

            if (json.lettersFound == 0) {
                isLose = true;
                alert('No letters found. :)');
            }
            if (json.word.indexOf('#') == -1)
            {
                //ai player wins
                alert('winner!');
                window.location = highScoreURL;
            }
            if (isLose) {
                nextPlayer(st);
                this.state = 'board';
            }
            else {
                st.scoreboxes[st.playerIndex].score += value * json.lettersFound;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error :" + XMLHttpRequest.responseText);
        }
    });
    st.state = 'board';
}

function SolveThePuzzle(st, sentence, points) {
    $.ajax({
        url: baseURL + 'home/SolvePuzzle',
        type: 'post',
        cache: false,
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data:JSON.stringify({guess: sentence, potentialPoints:points} ),
        success: function (json) {
            if(json === true)
            {
                alert('winner!');
                window.location = highScoreURL;
            }
            else {
                alert("wrong guess!");
                nextPlayer(st);
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("error :" + XMLHttpRequest.responseText);
        }
    });
}